package hot100.logos51To60;

/**
 * @author logos
 * date 2025/7/14 17:54
 * @version v1.0
 * @Package hot100.logos51To60
 */
public class logos51 {

    /**
     * 51. 岛屿数量
     * https://leetcode.cn/problems/number-of-islands/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        public int numIslands(char[][] grid) {
            int n = grid.length;
            int m = grid[0].length;
            int ans = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (grid[i][j] == '1') {
                        ans++;
                        dfs(grid, i, j);
                    }
                }
            }
            return ans;
        }

        private void dfs(char[][] grid, int i, int j) {
            int n = grid.length;
            int m = grid[0].length;
            if (i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == '0') {
                return;
            }
            grid[i][j] = '0';
            dfs(grid, i + 1, j);
            dfs(grid, i, j + 1);
            dfs(grid, i - 1, j);
            dfs(grid, i, j - 1);
        }
    }
}
